package edu.cmu.cs.cs214.hw9.client.controllers.eventhandlers;

import java.util.List;

import javax.swing.SwingWorker;

import edu.cmu.cs.cs214.hw9.client.controllers.BackendCacheAdapter;
import edu.cmu.cs.cs214.hw9.client.controllers.SessionController;
import edu.cmu.cs.cs214.hw9.client.gui.FriendsScreen;
import edu.cmu.cs.cs214.hw9.datatypes.User;

/**
 * Goes to the currently logged in user's list of friends.
 */
public class GotoFriendsHandler extends SessionEventHandler {
	// Encapsulates the list of pending and current friends that the currently
	// logged in user has.
	private class FriendsData {
		List<User> pendingFriends;
		List<User> currentFriends;
	}
	
	/**
	 * Obtain friends lists in a separate thread to prevent swing from freezing.
	 */
	private class FriendsWorker extends SwingWorker<FriendsData, Void> {
		private BackendCacheAdapter model;
		private User currentUser;
		
		/**
		 * Construct the friend list data request.
		 */
		public FriendsWorker() {
			currentUser = controller.getCurrentUser();
			model = controller.getModel();
		}
		
		/**
		 * Get the friends lists from the database. 
		 * 
		 * @return Friends lists. Note that lists may be empty.
		 */
		public FriendsData doInBackground() {
			FriendsData result = new FriendsData();
			result.pendingFriends = model.getFriendRequests(currentUser);
			result.currentFriends = model.getFriends(currentUser);
			
			return result;
		}
		
		/**
		 * Redirect the user to the friends list page.
		 */
		public void done() {
			try {
				FriendsData data = get();
				changeScreen(new FriendsScreen(data.pendingFriends, data.currentFriends));
			} catch (Exception e) {
				throw new RuntimeException("Fatal error occured when switching to friends screen: " + e.getMessage());
			}
		}
	};
	
	/**
	 * Set the current session controller to the provided controller.
	 * 
	 * @param controller Controller to associate with this event handler.
	 */
	public GotoFriendsHandler(SessionController controller) { super(controller); }
	
	/**
	 * Create the friends list request and run it in an outside thread.
	 * 
	 * @param param Not used; can be anything.
	 */
	public void handleEvent(Object param) {
		FriendsWorker friendsWorker = new FriendsWorker();
		
		friendsWorker.execute();
	}
}
